package com.nyt.org.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class SendPostRequest {

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, String json){
        //创建HttpClient
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        //post请求
        HttpPost post = new HttpPost(url);

        JSONObject responseJSON = null;

        String result = null ;

        try {
            //设置发送请求格式
            StringEntity s = new StringEntity(json.toString(),"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/xml;charset=UTF-8");//发送json数据需要设置contentType
            post.setEntity(s); //设置编码
            //发送请求
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(res.getEntity(),"UTF-8");// UTF-8
                //response = JSONObject.fromObject(result);
                //字符串转换成JSON对象
                //responseJSON =JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //System.out.println("**********  返回的responseJSON  **********");
        //System.out.println(responseJSON);
        return result;
    }



}
